<?php

namespace App\Services;

use App\Exceptions\ExceptionApi;
use Catmes\HttpClient\Curl;

class Sms
{
    private $userid,$username,$password,$serverurl;
    private $result,$usersign;


    public function __construct()
    {
        $this->serverurl='http://123.57.51.191:8888/v2sms.aspx';
        $this->userid=Config::get(Config::KEY_SMS_USER_ID);
        $this->username=Config::get(Config::KEY_SMS_USERNAME);
        $this->password=Config::get(Config::KEY_SMS_PASSWORD);
        $this->usersign=Config::get(Config::KEY_SMS_SIGN_TAG);
    }

    /**
     * 发送短信
     * @param $phone
     * @param $content
     * @param string $sendtime
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function send($phone,$content,$sendtime=''){
        $timestamp=date('YmdHis');
        $sign=$this->getSign($timestamp);
        $content='【'.$this->usersign.'】'.$content;
        $param=[
            'action'=>'send',
            'userid'=>$this->userid,
            'timestamp'=>$timestamp,
            'sign'=>$sign,
            'mobile'=>$phone,
            'content'=>$content,
            'sendTime'=>$sendtime,
            'extno'=>''
        ];
        $msg = '短信发送失败';
        $response = (new Curl($this->serverurl, 'post', $param))
            ->postUrlEncoded()->getResponse();
        if($response->getStatusCode()!=200){
            throw new ExceptionApi($msg);
        }
        $xml = $response->getBody();
        $this->result = $xml;
        $xmlObj = simplexml_load_string($xml);
        if(!$xmlObj){
            Logger::debug($this->result);
            throw new ExceptionApi($msg);
        }
        if($xmlObj->returnstatus != 'Success'){
            Logger::debug($this->result);
            throw new ExceptionApi($msg);
        }
//        $xmlJson= json_encode($xmlObj);
//        $xmlArr=json_decode($xmlJson,true);

    }
/*
$xml = <<<XML
<?xml version="1.0" encoding="utf-8" ?><returnsms>
 <returnstatus>Success</returnstatus>
 <message>ok</message>
 <remainpoint>46085</remainpoint>
 <taskID>14141681</taskID>
 <successCounts>1</successCounts></returnsms>
XML;
*/

    /**
     * 获取请求签名
     * @param $timestamp
     * @return string
     */
    private function getSign($timestamp){
        return md5($this->username.$this->password.$timestamp);
    }

    /**
     * 验证短信次数
     * @param $phone
     * @return int
     */
    public function checksmscount($phone){
    }

    /**
     * 记录发送次数
     * @param $phone
     */
    public function recordsmscount($phone){
    }

}
